package com.tian.print.http.response;


import com.tian.print.http.error.ApiException;
import com.tian.print.http.error.ExceptionHandler;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.functions.Function;

/**
 * Description: 对返回数据进行处理,区分异常情况
 * <br>Author：tian
 * <br>Time: 2019/5/24 11:55
 */
public class ResponseTransformer {

    public static <T> ObservableTransformer<Response<T>, T> handleResult() {
        return new ObservableTransformer<Response<T>, T>() {
            @Override
            public ObservableSource<T> apply(Observable<Response<T>> upstream) {
                return upstream.onErrorResumeNext(new ErrorFunction<T>()).flatMap(new ResponseFuction<T>());
            }
        };
    }

    /**
     * 非服务器产生的异常,如本地没有网络json解析错误等
     *
     * @param <T>
     */
    private static class ErrorFunction<T> implements Function<Throwable, ObservableSource<? extends Response<T>>> {
        @Override
        public ObservableSource<? extends Response<T>> apply(Throwable throwable) {
            return Observable.error(ExceptionHandler.handleException(throwable));
        }
    }

    /**
     * 服务其返回的数据解析
     * 正常服务器返回数据和服务器可能返回的exception
     *
     * @param <T>
     */
    private static class ResponseFuction<T> implements Function<Response<T>, ObservableSource<T>> {
        @Override
        public ObservableSource<T> apply(Response<T> tResponse) throws Exception {
            int code = tResponse.getCode();
            //成功
            if (code == 1) {
                return Observable.just(tResponse.getData());
            } else {
                return Observable.error(new ApiException(code, tResponse.getMsg()));
            }
        }
    }

}
